"use strict";

/**
 * @ngdoc directive
 * @name jgappApp.directive:userDefined
 * @description
 * # userDefined
 */
angular
  .module("jgappApp")
  .directive("userDefined", function (
    Util,
    $http,
    openApi,
    DataService,
    $routeParams
  ) {
    return {
      scope: {
        uid: "=uid",
        param: "=param",
        processid: "=processid",
        fieldMap: "=fieldMap",
        validation: "=validation"
      },
      templateUrl: "views/userdefined/usertemp.html",
      restrict: "AE",
      replace: true,
      link: function postLink(scope, element, attrs) {
        var routeConfig = Util.getRouteConfig();
        var functionId = routeConfig.functionId;
        var formKey, fieldName, formtype;
        // 数据要从接口中拿到，不然由于异步原因无法拿到fieldMap值
        scope.formData = {};
        scope.searchinput = ""
        // 如果是审批页面只做展示
        var fieldMap = scope.fieldMap || {};
        scope.changeHandle = function () {
          megFieldMap();
          // 获取验证信息
          scope.validation = getValidation();
          scope.fieldMap = fieldMap;
        };
        // fieldType为7 start
        scope.getFrequentConcerns = function (key, data) {
          scope.conKey = key;
          fieldName = data.fieldName;
          formKey = fieldName.split("#")[0];
          scope.search2({ formKey: formKey })
          Util.frequentConcern({ scope: scope });
        };

        scope.search2 = function (params) {
          var param = Object.assign({}, params);;
          param.limit = 30;
          param.name = scope.searchinput
          console.log(param);
          // DataService.getData(openApi.getFrequentConcerns, param).then(function (
          DataService.getData(openApi.users, param).then(function (
            data
          ) {
            if (data) {
              scope.users = data;
            } else {
              Util.Toast("没有抄送人");
            }
          });
        };
        // fieldType为8 start
        scope.getFieldType8Data = function (key, data) {
          formtype = 1;
          scope.conKey = key;
          fieldName = data.fieldName;
          formKey = fieldName.split("#")[0];
          var param = {};
          param.formKey = formKey;
          param.functionId = functionId || -1;
          param.relatedModule = "selectApproveType";
          getFieldType8Data(param);
        };
        scope.getFieldType9Data = function (key, data) {
          formtype = 2;
          scope.conKey = key;
          fieldName = data.fieldName;
          formKey = data.hideProperty.split("#")[0];
          functionId = data.hideProperty.split("#")[1];
          var param = {};
          param.formKey = formKey;
          param.functionId = functionId || -1;
          param.fieldName = fieldName;
          getFieldType9Data(param);
        };

        function getFieldType8Data(param) {
          var postData = {};
          postData.url = openApi.getRelpage;
          postData.dataType = "json";
          postData.method = "POST";
          postData.data = param;
          $http(postData).then(function (data) {
            data = data.data;
            if (data.logout) {
              Util.logout();
              return;
            }
            if (data.success) {
              scope.sptypes = data.dataList;
              scope.porlist = data.displayPropertys;
              scope.valuePropertys = data.valuePropertys;
              scope.placeholder = data.searchName;
              Util.perlist({ scope: scope });
            } else {
              Util.Toast(data.result);
            }
          });
        }
        function getFieldType9Data(param) {
          var postData = {};
          postData.url = openApi.getModuleCustomfield;
          // postData.dataType = "json";
          postData.method = "POST";
          postData.data = param;
          $http(postData).then(function (data) {
            data = data.data;
            if (data.logout) {
              Util.logout();
              return;
            }
            if (data.success) {
              scope.sptypes = data.dataList;
              scope.porlist = data.displayPropertys;
              scope.valuePropertys = data.valuePropertys;
              scope.placeholder = data.searchName;
              Util.perlist({ scope: scope });
            } else {
              Util.Toast(data.result);
            }
          });
        }
        scope.choosePeople = function (index) {
          var filterData = Util.filterSelectData(
            scope.sptypes[index],
            scope.valuePropertys
          );
          scope.formData[scope.conKey].value = filterData[scope.conKey];
          scope.param = angular.extend({}, scope.param, filterData);
          scope.filterSql = "";
          delete scope.param[scope.conKey];
          scope.changeHandle();
          Util.closeMasker();
        };
        scope.search = function (filterSql) {
          if (formtype == 1) {
            search(filterSql);
          } else {
            search2(filterSql);
          }
        };
        var search = function (filterSql) {
          var param = {};
          param.formKey = formKey;
          param.functionId = functionId || -1;
          param.relatedModule = "selectApproveType";
          param.filterSql = filterSql;
          scope.filterSql = filterSql;
          getFieldType8Data(param);
        };
        var search2 = function (filterSql) {
          var param = {};
          param.formKey = formKey;
          param.functionId = functionId || -1;
          param.fieldName = fieldName;
          param.filterSql = filterSql;
          scope.filterSql = filterSql;
          getFieldType9Data(param);
        };

        scope.selectUsers = function (user) {
          for (let index = 0; index < scope.users.length; index++) {
            const curuser = scope.users[index];
            if (curuser.name === user.name) {
              curuser.selected = !user.selected
            }
          }
          console.log(scope.users);
          scope.$apply()
        };

        scope.chooseusers = function () {
          var selectUsers = scope.users.filter(function (user) {
            return user.selected
          })
          if (selectUsers.length === 0) {
            Util.Toast("请选择抄送人");
            return
          }
          const names = selectUsers.map(function (user) {
            return user.name
          }).join(",");
          console.log(names);
          scope.formData[scope.conKey].value = names
          scope.changeHandle();
          Util.closeMasker();
        };
        // fieldType为7 end

        var getValidation = function () {
          var validation = {
            passvalidation: true,
            tip: ""
          };
          for (var i in scope.formData) {
            if (scope.formData[i].allowBlank == 0) {
              if (!scope.formData[i].value && !scope.formData[i].defaultValue) {
                validation.passvalidation = false;
                validation.tip = "请输入" + scope.formData[i].fieldLabel;
                break;
              }
            }
          }
          return validation;
        };
        var megFieldMap = function () {
          for (var i in scope.formData) {
            if (scope.formData[i].value) {
              fieldMap[i] = scope.formData[i].value.toString();
            } else {
              fieldMap[i] = scope.formData[i].defaultValue;
            }
          }
        };
        var updateOrNewForm = function (uid) {
          var param = {};
          param.formKey = Util.getformKey();
          // 如果是驳回的则带上参数
          if (uid) {
            param.uid = uid;
          }
          param.taskId = $routeParams.id;
          // 新增流程有functionId，编辑时候没有
          param.functionId = functionId || (scope.param && scope.param.functionId);
          DataService.getData(openApi.customFields, param).then(function (data) {
            // 显示数据
            if (data) {
              scope.show = true;
              scope.formData = data;
              for (var i in scope.fieldMap) {
                if (scope.formData[i]) {
                  scope.formData[i].value = scope.fieldMap[i];
                }
              }
            }
            scope.changeHandle();
          });
        };
        var init = function () {
          var TVtype;
          // 如果是驳回的则带上参数
          TVtype = Util.getTVType();
          if (TVtype == Util.UPDATE) {
            scope.$watch("processid", function () {
              if (scope.processid) {
                if (scope.uid) {
                  updateOrNewForm(scope.uid);
                } else {
                  updateOrNewForm();
                }
              }
            });
          } else {
            updateOrNewForm();
          }
        };
        init();
      }
    };
  });
